package org.javarosa.view;

import java.util.Timer;
import java.util.TimerTask;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Spacer;
import javax.microedition.lcdui.StringItem;

import org.javarosa.core.api.IView;
import org.javarosa.formmanager.view.SubmitStatusScreen;

public class MessageWithRefreshScreen extends Form implements CommandListener, IView {
	
	// MODEL VARIABLES
    private StringItem messageTextView;
    private IMessageRefreshController refreshController;
	private int counter = 0;
	private Timer timer;
    private Command okCommand;

    // BUSINESS METHODS
    
	public MessageWithRefreshScreen (String title, IMessageRefreshController refreshController) {
		
    	//#style submitPopup
		super(title);
		okCommand = new Command("OK", Command.OK, 1);
		
		this.messageTextView = new StringItem(null, "");
		this.setCommandListener(this);
		
		this.refreshController = refreshController;

		addCommand(okCommand);
		append(new Spacer(80, 0));
		append(this.messageTextView);
				
		timer = new Timer();
		timer.schedule(new TimerTask () {
			public void run () {
				if(MessageWithRefreshScreen.this.shouldBeContinue()){
					counter += SubmitStatusScreen.REFRESH_INTERVAL;
				}
				MessageWithRefreshScreen.this.refresh();
			}
		}, 
		SubmitStatusScreen.REFRESH_INTERVAL, 
		SubmitStatusScreen.REFRESH_INTERVAL);
	}


	protected boolean shouldBeContinue() {
		return this.refreshController.shouldBeContinue();
	}


	protected void refresh() {
		this.setMessage(this.refreshController.getMessage());
	}

	public void setMessage(String message) {
		this.messageTextView.setText(message);		
	}

	public void commandAction(Command c, Displayable d) {
		if(d == this){
			this.timer.cancel();
			this.timer = null;
			this.refreshController.exit();
		}
	}

	public Object getScreenObject() {
		// TODO Auto-generated method stub
		return this;
	}

}
